import { defineStore } from 'pinia';

import { getInfo, login } from '@/api/userController';
import { usePermissionStore } from '@/store';
import type { UserInfo } from '@/types/interface';

const InitUserInfo: UserInfo = {
  id: 0,
  account: '',
  username: 'td_admin',
  role: [],
  status: 0,
  avatarUrl: '',
};

export const useUserStore = defineStore('user', {
  state: () => ({
    token: '',
    userInfo: { ...InitUserInfo },
  }),
  // getters: {
  //   roles: (state) => {
  //     return state.userInfo?.roles;
  //   },
  // },
  actions: {
    async login(userInfo: Record<string, unknown>) {
      // 登录请求流程
      console.log(`用户登录信息:`, userInfo);
      const res = await login(userInfo);
      const { code } = res.data;
      if (code === 200) {
        this.token = res.data.data.token;
        this.userInfo = await this.getUserInfo();
      } else {
        throw res;
      }
    },

    async getUserInfo() {
      const info = await getInfo();
      console.log(`info:`, info);
      if (info.data.code === 200) {
        return info.data.data;
      } else {
        throw info;
      }
    },

    async logout() {
      this.token = '';
      this.userInfo = { ...InitUserInfo };
    },
  },
  persist: {
    afterRestore: () => {
      const permissionStore = usePermissionStore();
      permissionStore.initRoutes();
    },
    key: 'user',
    paths: ['token', 'userInfo'],
  },
});
